//
// Created by hsj on 2023-12-29.
// ！！！window平台代码，Windows MinGW64编译！！！
// 编译：gcc hello_client_win.c -LH:\mingw\mingw64\x86_64-w64-mingw32\lib -lws2_32 -o hello_client_win
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
//inet_pton函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>

void ErrorHandling(char *message);

int main(int argc, char *argv[]){
    WSADATA wsaData;
    SOCKET hSocket;
    SOCKADDR_IN servAddr;

    char message[30];
    int strLen;
    char ip[]="127.0.0.1";
    char port[]="6788";

    if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
        ErrorHandling( "WSAStartup() error!");
    hSocket=socket(PF_INET, SOCK_STREAM, 0);
    if(hSocket==INVALID_SOCKET)
        ErrorHandling(" socket() error");

    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family=AF_INET;
    servAddr.sin_port=htons(atoi(/*argv[2]*/port));
    inet_pton(AF_INET, ip, &servAddr.sin_addr.s_addr);//servAddr.sin_addr.s_addr=inet_addr(/*argv[1]*/ip);

    if(connect(hSocket, (SOCKADDR* )&servAddr, sizeof(servAddr))==SOCKET_ERROR)
        ErrorHandling("connect() error!");

    memset(message, 0, sizeof(message));
    strLen=recv(hSocket, message, sizeof(message)-1, 0);//少一，保证'\0'结尾
    if(strLen==-1)
        ErrorHandling("read() error!");
    printf("Message from server: %s \n", message);
    closesocket(hSocket);
    WSACleanup();

    return EXIT_SUCCESS;
}


void ErrorHandling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}